package com.be.beadmin.quality.controller;

import cn.hutool.core.date.DateUtil;
import com.be.beadmin.common.exception.BeadminException;
//import com.be.beadmin.product.entity.ErrorReport;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.quality.dto.input.InspectionFileInfoByInspectionTypeAndIdPage;
import com.be.beadmin.quality.entity.InspectionFileInfo;
import com.be.beadmin.quality.dto.output.InspectionFileInfoEx;
import com.be.beadmin.quality.repository.InspectionFileInfoRepository;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Page;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.quality.service.InspectionFileInfoService;
import com.be.beadmin.quality.dto.input.InspectionFileInfoQueryCriteria;
import com.be.beadmin.quality.dto.input.InspectionFileInfoDto;
import org.springframework.data.domain.Pageable;
import com.be.beadmin.common.utils.ResultModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

/**
* @author ljh
* @date 2023-07-13
**/
@Api(tags = "检验附件管理")
@RestController
public class InspectionFileInfoController {

    @Autowired
    private  InspectionFileInfoService inspectionFileInfoService;

    @Autowired
    private InspectionFileInfoRepository inspectionFileInfoRepository;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private String bucketName = "inspectionfile";

    @PostMapping(value = "/quality/getInspectionFileInfoByPage")
    public ResultModel getInspectionFileInfoByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(inspectionFileInfoService.getInspectionFileInfoByPage(pageEntity)) ;
    }

    @ApiOperation("检验附件分页信息（By 检验类型+标识id（用于入厂检的入厂检验id/过程检验的生产工序id/...））")
    @PostMapping(value = "/quality/getInspectionFileInfoByPageAndInspectionTypeAndId")
    public ResultModel getInspectionFileInfoByPageAndInspectionTypeAndId(@RequestBody InspectionFileInfoByInspectionTypeAndIdPage inspectionFileInfoByInspectionTypeAndIdPage)  {
        try {
            return ResultModel.success(inspectionFileInfoService.getInspectionFileInfoByPageAndInspectionTypeAndId(inspectionFileInfoByInspectionTypeAndIdPage)) ;
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }
      }

    @ApiOperation("上传检验附件")
    @PostMapping("/quality/uploadInspectionFileInfo")
    public ResultModel uploadInspectionFileInfo(
            @ApiParam(value = "检验类型",required = true) @RequestParam String inspectionType,
            @ApiParam(value = "标识id（用于入厂检的入厂检验id/过程检验的生产工序id/...）",required = true) @RequestParam String id,
            @ApiParam(value = "上传人id",required = true) @RequestParam String uploaderId,
            @ApiParam(value = "上传人姓名",required = true) @RequestParam String uploaderName,
            @ApiParam(value = "上传时间",required = true) @RequestParam String uploadTime,
            @ApiParam(value = "检验附件上传",required = true) @RequestParam( value= "file" ) MultipartFile[] multipartFile
    ){
        try {
                inspectionFileInfoService.uploadInspectionFileInfo(inspectionType, id, uploaderId, uploaderName, DateUtil.parse(uploadTime), multipartFile, bucketName);
            return ResultModel.success(ResultModel.ADD);
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }
    }

    @ApiOperation("获得pdf、图片的预览url")
    @PostMapping("/quality/getInspectPreviewUrl")
    public ResultModel getInspectPreviewUrl(@RequestBody InspectionFileInfoDto inspectionFileInfoDto) throws Exception {
        String previewUrl =  inspectionFileInfoService.getInspectPreviewUrl(inspectionFileInfoDto);
        return ResultModel.success(previewUrl);
    }

    @ApiOperation("自检附件下载")
    @GetMapping("/quality/downloadInspectionFile")
    @ResponseBody
    public void downloadErrorReportFile(@ApiParam(value = "入厂检附件Id")@RequestParam String inspectionFileId,
                                        HttpServletResponse response) throws Exception {
        try {
            InspectionFileInfo inspectionFileInfo = inspectionFileInfoRepository.findInspectionFileInfoByIdAndDelete(inspectionFileId,0);
            String bucketName = inspectionFileInfo.getBucketName();
            String fileName = inspectionFileInfo.getInspectionFileName();
            String fileCode = inspectionFileInfo.getInspectionFileCode();
            String downloadFileName= fileCode+"+"+fileName;
            InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+fileName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            //  return  ResultModel.success("下载成功");
        } catch (Exception e) {
            // return ResultModel.error(99,"文件读取异常");
        }
    }

    @PostMapping("/quality/addInspectionFileInfo")
    public ResultModel addInspectionFileInfo(@RequestBody InspectionFileInfoDto inspectionFileInfoDto){
        inspectionFileInfoService.addInspectionFileInfo(inspectionFileInfoDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/quality/delInspectionFileInfo")
    public ResultModel delInspectionFileInfo(@RequestBody InspectionFileInfoDto inspectionFileInfoDto){
        inspectionFileInfoService.delInspectionFileInfo(inspectionFileInfoDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/quality/updateInspectionFileInfo")
    public ResultModel updateInspectionFileInfo(@RequestBody InspectionFileInfoDto inspectionFileInfoDto){
        inspectionFileInfoService.updateInspectionFileInfo(inspectionFileInfoDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/quality/exportInspectionFileInfo")
    public void exportInspectionFileInfo(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<InspectionFileInfoEx> inspectionFileInfoPage = inspectionFileInfoService.getInspectionFileInfoByPage(pageEntity);
        List<InspectionFileInfoEx> inspectionFileInfoExes = inspectionFileInfoPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("InspectionFileInfo接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), InspectionFileInfoEx.class).sheet("sheet1").doWrite(inspectionFileInfoExes);
    }
}